<template>
  <div class="basic-box">
    <div class="container-box">
      <div class="header">
        <div class="left">
          <!--          <el-image class="cover" :src="activityDetail.logo" style="width: 200px" />-->
          <div>
            <div class="activity-name">{{ activityDetail.name }}</div>
            <div v-for="(item,index) in activityMap" :key="index" class="cell">
              <div v-if="item.key !== 'intro' && item.key !== 'activityName' " class="title">
                {{ item.title }} :&nbsp;
              </div>
              <div v-if="item.key !== 'intro' && item.key !== 'activityName'" class="content">
                {{ activityDetail[item.key] }}
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <el-button icon="el-icon-edit" type="primary" @click="handleUpdate">编辑</el-button>
        </div>
      </div>
      <!--      <div class="summary">-->
      <!--        <div class="summary-title">-->
      <!--          活动简介 :-->
      <!--        </div>-->
      <!--        <div class="summary-content" v-html="activityDetail.intro" />-->
      <!--      </div>-->
    </div>
    <div class="container-box">
      <div class="table-title text-primary"> 参与社团</div>
      <div class="filter-container" style="display: flex; flex-direction: row;justify-content: flex-end">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate('org')">
          添加社团
        </el-button>
        <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          下载数据
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="orgList"
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="#ID" prop="id" sortable="custom" align="center" width="100">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="社团名称" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="社团级别" align="center" width="95">
          <template slot-scope="{row}">
            <span>{{ row.level }}</span>
          </template>
        </el-table-column>
        <el-table-column label="人数" align="center" width="95">
          <template slot-scope="{row}">
            <span>{{ row.num }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" min-width="100px">
          <template slot-scope="{row}">
            <span class="link-type"> {{ row.principal }} </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" align="center" min-width="180" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="toDetail(row.id,'org')">
              详情
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index,'org')">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      <pagination v-show="listQuery.orgList.total > 0" :total="listQuery.orgList.total" :page.sync="listQuery.orgList.page" :limit.sync="listQuery.orgList.limit" @pagination="fetchInfo" />-->
    </div>
    <div class="container-box">
      <div class="table-title text-primary"> 参与社团成员</div>
      <div class="filter-container" style="display: flex; flex-direction: row;justify-content: flex-end">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate('member')">
          添加成员
        </el-button>
        <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          下载数据
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="memberList"
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="#学号" prop="id" sortable="custom" align="center" width="100">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" width="95">
          <template slot-scope="{row}">
            <span>{{ row.gender }}</span>
          </template>
        </el-table-column>
        <el-table-column label="班级" align="center" min-width="100px">
          <template slot-scope="{row}">
            <span class="link-type">{{ row.title }}</span>
            <span>{{ row.uclass }}</span>
          </template>
        </el-table-column>

        <el-table-column label="Status" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="toDetail(row.id, 'member')">
              详情
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index,'member')">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--      <pagination v-show="listQuery.memberList.total>0" :total="listQuery.memberList.total" :page.sync="listQuery.memberList.page" :limit.sync="listQuery.memberList.limit" @pagination="getMemberList" />-->
    </div>

    <el-dialog title="编辑活动信息" :visible.sync="dialogFormVisible">
      <el-form ref="activity" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="发起人" prop="orgUser">
          <el-cascader v-model="temp.orgUser" :value="temp.orgUser" :options="orgMemberOptions" />
        </el-form-item>
        <el-form-item label="举办场所" prop="need">
          <el-input v-model="temp.need" />
        </el-form-item>
        <el-form-item label="活动时间" prop="dateSpan">
          <el-date-picker
            v-model="temp.dateSpan"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="预计规模" prop="scale">
          <el-input v-model.number="temp.scale" placeholder="活动大致参与人数" />
        </el-form-item>
        <el-form-item label="开放程度" prop="openScale">
          <el-select v-model="temp.openScale" style="width: 300px" placeholder="请选择">
            <el-option v-for="item in options.openScaleOptions" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <div class="text-danger">*参与者在详情处设置</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="删除确认" :visible.sync="deleteDialogFormVisible" style="width: 450px;margin: 0 auto" @close="cancelDelete">
      <div ref="dataForm" style="width: 100%;" class="text-danger">
        <span><i class="el-icon-warning-outline" /></span>
        删除数据将无法恢复
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDelete">
          取消
        </el-button>
        <el-button type="danger" @click="deleteData">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="addDialogTitle" :visible.sync="addDialogFormVisible">
      <div class="filter-container" style="display: flex; flex-direction: row;justify-content: flex-end">
        <el-input v-model="listQuery.addDialog.title" :placeholder="'输入要添加的' + (addType === 'org' ? '社团' : '人员') + '名称' " style="width: 200px;" class="filter-item" />
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="getAddDialogList">
          搜索
        </el-button>
      </div>
      <el-table :data="gridData">
        <el-table-column :label="(addType === 'org' ? '社团id': '学号' )" prop="id" align="center" min-width="100">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="(addType === 'org' ? '社团' : '人员') + '名称'" prop="name" align="center" min-width="100">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" align="center" width="100" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-plus" type="success" size="mini" @click="handleAdd(row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="listQuery.addDialog.total>0" :total="listQuery.addDialog.total" :page-sizes="[5]" :page.sync="listQuery.addDialog.page" :limit.sync="listQuery.addDialog.limit" @pagination="getAddDialogList" />
    </el-dialog>

    <!--    <div class="container-box" style="display: flex;flex-direction: row;">-->
    <!--      <div id="chart" style="width: 100%;height: 400px" />-->
    <!--    </div>-->
  </div>

</template>

<script>
import { addActivityBasic, fetchActivityDetail } from '@/api/activity'
import echarts from 'echarts'
import { fetchOrgList, fetchOrgNames } from '@/api/com'
import { fetchMemberList } from '@/api/member'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'
import { getOrgMemberOptions } from '@/api/user'
const options = {
  status: [
    { value: '0', label: '拒绝' },
    { value: '1', label: '申请中' },
    { value: '2', label: '接受' },
    { value: '3', label: '已过期' },
    { value: '4', label: '全选' }
  ],
  hostOrg: [
    {
      value: '计算机服务队',
      label: '计算机服务队'
    }, {
      value: '软件俱乐部',
      label: '软件俱乐部'
    }, {
      value: '自行车协会',
      label: '自行车协会'
    }, {
      value: '红会',
      label: '红会'
    }, {
      value: '学生会',
      label: '学生会'
    }
  ],
  searchType: [
    { value: 'name', label: '社团名称' },
    { value: 'principal', label: '负责人' },
    { value: 'level', label: '社团级别' }
  ],
  openScaleOptions: [
    { name: '社团内部开放' },
    { name: '校内开放' },
    { name: '对所有人开放' }
  ]
}
export default {
  name: 'ActivityDetail',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '活跃': 'success',
        '暂停': 'info',
        '解散': 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      id: this.$route.params.id,
      isEditMode: false,
      listLoading: false,
      downloadLoading: false,
      addDialogFormVisible: false,
      deleteDialogFormVisible: false,
      dialogFormVisible: false,
      gridData: [],
      deleteType: '',
      memberList: [],
      addType: '',
      addDialogTitle: '',
      listQuery: {
        activityDetail: {
          org: '',
          title: '',
          page: 1,
          limit: 10,
          onlyWorking: true,
          vague: true
        },
        orgList: {
          org: '',
          total: 0,
          title: '',
          page: 1,
          limit: 10,
          names: [],
          vague: true
        },
        memberList: {
          org: '',
          title: '',
          total: 0,
          page: 1,
          limit: 10,
          names: [],
          onlyWorking: true,
          vague: false
        },
        addDialog: {
          title: '',
          total: 0,
          page: 1,
          limit: 5,
          type: 'name',
          onlyWorking: true,
          status: null
        }
      },
      options,
      orgMemberOptions: null,
      orgOptions: null,
      tableKey: 0,
      activityDetail: {},
      temp: {
        id: null,
        name: null,
        hostUid: null,
        hostOrg: null,
        hostOid: null,
        hostname: null,
        scale: null,
        openScale: null,
        stDate: null,
        endDate: null,
        status: null,
        need: null,
        participant: [],
        participantOrg: [],
        orgUser: []
      },
      editData: {},
      categoryList: [
        { value: '0', label: '禁用' },
        { value: '1', label: '启用' }
      ],
      activityMap: [
        { key: 'name', title: '活动名称' },
        { key: 'hostname', title: '发起人' },
        { key: 'hostOrg', title: '发起社团' },
        { key: 'status', title: '状态' },
        { key: 'scale', title: '规模' },
        { key: 'openScale', title: '开放状态' },
        { key: 'intro', title: '活动简介' }
      ],
      orgList: [],
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'change' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'change' }
        ],
        orgUser: [
          { required: true, message: '请选择活动发起人', trigger: 'change' }
        ],
        need: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        dateSpan: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        scale: [
          { required: true, message: '请输入活动规模', trigger: 'change', type: 'number' }
        ],
        openScale: [
          { required: true, message: '请选择活动开放程度', trigger: 'change' }
        ],
        participantOrg: [
          { required: true, message: '请选择活动参与的社团', trigger: 'change' }
        ]
      }
    }
  },

  mounted() {
    this.fetchInfo()
    getOrgMemberOptions().then(res => { this.orgMemberOptions = res.data.items })
    fetchOrgNames().then(res => { this.orgOptions = res.data.items })
  },
  methods: {
    setTagsViewTitle() {
      this.$route.meta.title = this.activityDetail.name
      const currentView = this.$store.getters.visitedViews[this.$store.getters.visitedViews.findIndex(
        (item) => item.path === this.$route.path
      )]
      if (currentView != null) {
        currentView.title = this.activityDetail.name
      }
    },
    toDetail(id, type) {
      if (type === 'org') {
        this.$router.push({ path: '/org-info/detail/' + id })
      } else {
        this.$router.push({ path: '/member/detail/' + id })
      }
    },
    handleCreate(type) {
      this.addType = type
      this.addDialogTitle = '添加参与' + (type === 'org' ? '社团' : '用户')
      this.addDialogFormVisible = true
      this.getAddDialogList()
    },
    handleAdd(row) {
      this.temp = Object.assign({}, this.activityDetail)
      this.temp['dateSpan'] = []
      this.temp['orgUser'] = [Number(this.temp.hostOid), Number(this.temp.hostUid)]
      this.temp.dateSpan.push(this.temp.stDate)
      this.temp.dateSpan.push(this.temp.endDate)
      if (this.addType === 'org') {
        if (!this.temp.participantOrg.includes(row.id)) { this.temp.participantOrg.push(row.id) } else {
          this.$notify({
            title: 'Error',
            message: '不可重复添加社团',
            type: 'error',
            duration: 2000
          })
          return
        }
      } else {
        if (!this.temp.participant.includes(row.id)) {
          this.temp.participant.push(row.id)
        } else {
          this.$notify({
            title: 'Error',
            message: '不可重复添加用户',
            type: 'error',
            duration: 2000
          })
          return
        }
      }
      this.updateData('add')
    },
    handleDelete(row, index, type) {
      this.temp = Object.assign({}, this.activityDetail)
      this.temp['dateSpan'] = []
      this.temp['orgUser'] = [Number(this.temp.hostOid), Number(this.temp.hostUid)]
      this.temp.dateSpan.push(this.temp.stDate)
      this.temp.dateSpan.push(this.temp.endDate)
      if (type === 'org') {
        this.temp.participantOrg.splice(this.temp.participantOrg.indexOf(Number(row.id)))
      } else {
        this.temp.participant.splice(this.temp.participant.indexOf(Number(row.id)))
      }
      this.deleteDialogFormVisible = true
    },
    cancelDelete() {
      this.deleteDialogFormVisible = false
    },
    deleteData() {
      this.updateData('delete')
    },
    getAddDialogList() {
      if (this.addType === 'org') {
        fetchOrgList(this.listQuery.addDialog).then(
          response => {
            this.listQuery.addDialog.total = response.data.total
            this.gridData = response.data.items
            setTimeout(() => {
              this.listLoading = false
            }, 200)
          })
      } else {
        fetchMemberList(this.listQuery.addDialog).then(
          response => {
            this.listQuery.addDialog.total = response.data.total
            this.gridData = response.data.items
            setTimeout(() => {
              this.listLoading = false
            }, 200)
          })
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchInfo()
    },
    setPageTitle() {
      document.title = `${this.activityDetail.name}`
    },
    fetchInfo() {
      this.listLoading = true
      fetchActivityDetail(this.id).then(res => {
        this.listQuery.total = res.data.total
        this.list = []
        this.memberList = res.data.items.users
        this.orgList = res.data.items.orgs
        const formItem = {
          id: res.data.items.id,
          name: res.data.items.name,
          hostUid: res.data.items.hostUser.id,
          hostOrg: res.data.items.hostOrg.name,
          hostOid: res.data.items.hostOrg.id,
          hostname: res.data.items.hostUser.name,
          scale: res.data.items.scale,
          openScale: res.data.items.openScale,
          stDate: new Date(res.data.items.stDate).getTime(),
          endDate: new Date(res.data.items.endDate).getTime(),
          status: res.data.items.status,
          need: res.data.items.need
        }
        formItem['participant'] = []
        formItem['participantString'] = ''
        formItem['participantOrgString'] = ''
        formItem['participantOrg'] = []
        for (const j in res.data.items.users) {
          formItem.participant.push(Number(res.data.items.users[j].id))
          formItem.participantString += res.data.items.users[j].name + ', '
        }
        for (const j in res.data.items.orgs) {
          formItem.participantOrgString += res.data.items.orgs[j].name + ', '
          formItem.participantOrg.push(Number(res.data.items.orgs[j].id))
        }
        formItem.participantString = formItem.participantString.substring(0, formItem.participantString.lastIndexOf(','))
        formItem.participantOrgString = formItem.participantOrgString.substring(0, formItem.participantOrgString.lastIndexOf(','))
        this.activityDetail = formItem
        this.setPageTitle()
        this.setTagsViewTitle()
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      })
    },
    handleUpdate() {
      this.temp = Object.assign({}, this.activityDetail)
      this.temp['dateSpan'] = []
      this.temp['orgUser'] = [Number(this.temp.hostOid), Number(this.temp.hostUid)]
      this.temp.dateSpan.push(this.temp.stDate)
      this.temp.dateSpan.push(this.temp.endDate)
      this.dialogFormVisible = true
    },
    updateData(formName) {
      if (formName === '') {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const form = Object.assign({}, this.temp)
            form.stDate = parseTime(form.dateSpan[0], '{y}-{m}-{d} {h}:{i}:{s}')
            form.endDate = parseTime(form.dateSpan[1], '{y}-{m}-{d} {h}:{i}:{s}')
            form.hostOid = form.orgUser[0]
            form.hostUid = form.orgUser[1]
            form.status = this.dialogStatus === 'create' ? '申请中' : form.status
            addActivityBasic(form).then(
              res => {
                if (res.status === 200) {
                  this.$notify({
                    title: 'Success',
                    message: 'Insert Successfully',
                    type: 'success',
                    duration: 2000
                  })
                  this.dialogFormVisible = false
                  this.fetchInfo()
                }
              }
            )
          } else {
            return false
          }
        })
      } else {
        const form = Object.assign({}, this.temp)
        form.stDate = parseTime(form.dateSpan[0], '{y}-{m}-{d} {h}:{i}:{s}')
        form.endDate = parseTime(form.dateSpan[1], '{y}-{m}-{d} {h}:{i}:{s}')
        form.hostOid = form.orgUser[0]
        form.hostUid = form.orgUser[1]
        form.status = this.dialogStatus === 'create' ? '申请中' : form.status
        addActivityBasic(form).then(
          res => {
            if (res.status === 200) {
              this.$notify({
                title: 'Success',
                message: 'Insert Successfully',
                type: 'success',
                duration: 2000
              })
              this.fetchInfo()
              this.addDialogFormVisible = false
              this.dialogFormVisible = false
              this.deleteDialogFormVisible = false
            }
          }
        )
      }
    },
    destroyDialog() {
      this.editData = {}
      this.isEditMode = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['学号', '姓名', '性别', '社团', '职位', '状态', '简介']
        const filterVal = ['id', 'name', 'gender', 'org', 'position', 'status', 'intro']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '社团成员表（总）'
        })
        this.downloadLoading = false
      })
    },
    initChart() {
      this.chart = echarts.init(document.getElementById('chart'))
      var option = {
        title: {
          text: '经费使用情况',
          subtext: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 484, name: '配件' },
              { value: 300, name: '海报' },
              { value: 1048, name: '未使用' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      this.chart.setOption(option)
    }
  }
}
</script>

<style scoped lang="scss">
  .container-box{
    margin: 20px;
    padding: 30px;
    border-radius: 5px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
  .table-title{
    font-weight: bolder;
    font-size: 25px;
    margin-bottom: 20px;
  }
  .basic-box{
    margin-top: 40px;
    padding: 30px 5%;
    border-radius: 10px;
    width: 100%;
  }
  .activity-name{
    font-size: 25px;
    color: #2c3e50;
    font-weight: bolder;
  }
  .header{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .left{
      width: 80%;
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      justify-content: flex-start;
      .cover{
        border-radius: 10px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
      }
    }
    .right{
      /*width: 20%;*/
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      /*margin-right: 20px;*/
      /*justify-content: flex-end;*/
    }
  }
  .cell{
    display: flex;
    flex-direction: row;
    align-items: center;
    margin:10px;
    .title{
      font-size: 20px;
      font-weight:800;
      color: #11A983;
    }
    .title-edit{
      font-size: 20px;
      font-weight:800;
      color: #11A983;
      width: 150px;
    }
    .content{
      font-size: 20px;
      font-weight: 500;
      width: 300px;
    }
  }
</style>
